package com.itzzj.common.aspect;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//@Aspect
//@Component
@Slf4j
public class MyAspect {

    @Around("execution(* com.itzzj.controller..*Controller.*(..))")
    public Object recordTimeLog(ProceedingJoinPoint joinPoint) throws Throwable {
        // 记录时间
        long begin = System.currentTimeMillis();
        // 获取 request 对象
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest req = sra.getRequest();
        log.info("请求地址：{}",req.getRequestURI());
        log.info("请求设备：{}",req.getHeader("user-agent"));
        // 获得参数
        Object[] args = joinPoint.getArgs();
        if(args != null && args.length > 0){
            for (int i = 0; i < args.length; i++) {
                if(args[i] instanceof HttpServletRequest ||
                        args[i] instanceof HttpServletResponse)
                    continue;
                log.info("参数：{}",args[i] == null ? "" : JSONUtil.toJsonStr(args[i]));
            }
        }

        // 执行目标
        Object result = joinPoint.proceed();
        log.info("响应：{}",JSONUtil.toJsonStr(result));

        // 记录时间
        long end = System.currentTimeMillis();
        long time = end - begin;

        log.info("执行时间：{}",time);
        return result;
    }
}






































